home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / url.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-03-23  |  26KB  |  611 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. URL parsing, construction and rendering.
  6. '''
  7. import weakref
  8. import urlparse
  9. import urllib
  10. from zope.interface import implements
  11. from twisted.web.util import redirectTo
  12. from nevow import inevow, flat
  13. from nevow.stan import raw
  14. from nevow.flat import serialize
  15. from nevow.context import WovenContext
  16.  
  17. def _uqf(query):
  18.     for x in query.split('&'):
  19.         if '=' in x:
  20.             yield []([ urllib.unquote_plus(s) for s in x.split('=', 1) ])
  21.             []
  22.             continue
  23.         tuple
  24.         if x:
  25.             yield (urllib.unquote_plus(x), None)
  26.             continue
  27.     
  28.  
  29.  
  30. unquerify = lambda query: list(_uqf(query))
  31.  
  32. class URL(object):
  33.     '''Represents a URL and provides a convenient API for modifying its parts.
  34.  
  35.     A URL is split into a number of distinct parts: scheme, netloc (domain
  36.     name), path segments, query parameters and fragment identifier.
  37.  
  38.     Methods are provided to modify many of the parts of the URL, especially
  39.     the path and query parameters. Values can be passed to methods as-is;
  40.     encoding and escaping is handled automatically.
  41.  
  42.     There are a number of ways to create a URL:
  43.         * Standard Python creation, i.e. __init__.
  44.         * fromString, a class method that parses a string.
  45.         * fromContext, a class method that creates a URL to represent the
  46.           current URL in the path traversal process.
  47.  
  48.     URL instances can be used in a stan tree or to fill template slots. They can
  49.     also be used as a redirect mechanism - simply return an instance from an
  50.     IResource method. See URLRedirectAdapter for details.
  51.  
  52.     URL subclasses with different constructor signatures should override
  53.     L{cloneURL} to ensure that the numerous instance methods which return
  54.     copies do so correctly.  Additionally, the L{fromString}, L{fromContext}
  55.     and L{fromRequest} class methods need overriding.
  56.  
  57.     @type fragment: C{str}
  58.     @ivar fragment: The fragment portion of the URL.
  59.     '''
  60.     
  61.     def __init__(self, scheme = 'http', netloc = 'localhost', pathsegs = None, querysegs = None, fragment = None):
  62.         self.scheme = scheme
  63.         self.netloc = netloc
  64.         if pathsegs is None:
  65.             pathsegs = [
  66.                 '']
  67.         
  68.         self._qpathlist = pathsegs
  69.         if querysegs is None:
  70.             querysegs = []
  71.         
  72.         self._querylist = querysegs
  73.         if fragment is None:
  74.             fragment = ''
  75.         
  76.         self.fragment = fragment
  77.  
  78.     
  79.     def path():
  80.         
  81.         def get(self):
  82.             return []([ urllib.quote(seg, safe = "-_.!*'()") for seg in self._qpathlist ])
  83.  
  84.         doc = '\n        The path portion of the URL.\n        '
  85.         return (get, None, None, doc)
  86.  
  87.     path = property(*path())
  88.     
  89.     def __eq__(self, other):
  90.         if not isinstance(other, self.__class__):
  91.             return NotImplemented
  92.         for attr in [
  93.             'scheme',
  94.             'netloc',
  95.             '_qpathlist',
  96.             '_querylist',
  97.             'fragment']:
  98.             if getattr(self, attr) != getattr(other, attr):
  99.                 return False
  100.         
  101.         return True
  102.  
  103.     
  104.     def __ne__(self, other):
  105.         if not isinstance(other, self.__class__):
  106.             return NotImplemented
  107.         return not self.__eq__(other)
  108.  
  109.     query = property((lambda self: [ '='.join((x, y)) for x, y in self._querylist ]))
  110.     
  111.     def _pathMod(self, newpathsegs, newqueryparts):
  112.         return self.cloneURL(self.scheme, self.netloc, newpathsegs, newqueryparts, self.fragment)
  113.  
  114.     
  115.     def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment):
  116.         '''
  117.         Make a new instance of C{self.__class__}, passing along the given
  118.         arguments to its constructor.
  119.         '''
  120.         return self.__class__(scheme, netloc, pathsegs, querysegs, fragment)
  121.  
  122.     
  123.     def fromString(klass, st):
  124.         (scheme, netloc, path, query, fragment) = urlparse.urlsplit(st)
  125.         u = netloc([], [], [ urllib.unquote(seg) for seg in path.split('/')[1:] ], unquerify(query), fragment)
  126.         return u
  127.  
  128.     fromString = classmethod(fromString)
  129.     
  130.     def fromRequest(klass, request):
  131.         '''
  132.         Create a new L{URL} instance which is the same as the URL represented
  133.         by C{request} except that it includes only the path segments which have
  134.         already been processed.
  135.         '''
  136.         uri = request.prePathURL()
  137.         if '?' in request.uri:
  138.             uri += '?' + request.uri.split('?')[-1]
  139.         
  140.         return klass.fromString(uri)
  141.  
  142.     fromRequest = classmethod(fromRequest)
  143.     
  144.     def fromContext(klass, context):
  145.         '''Create a URL object that represents the current URL in the traversal
  146.         process.'''
  147.         request = inevow.IRequest(context)
  148.         uri = request.prePathURL()
  149.         if '?' in request.uri:
  150.             uri += '?' + request.uri.split('?')[-1]
  151.         
  152.         return klass.fromString(uri)
  153.  
  154.     fromContext = classmethod(fromContext)
  155.     
  156.     def pathList(self, unquote = False, copy = True):
  157.         result = self._qpathlist
  158.         if unquote:
  159.             result = map(urllib.unquote, result)
  160.         
  161.         if copy:
  162.             result = result[:]
  163.         
  164.         return result
  165.  
  166.     
  167.     def sibling(self, path):
  168.         '''Construct a url where the given path segment is a sibling of this url
  169.         '''
  170.         l = self.pathList()
  171.         l[-1] = path
  172.         return self._pathMod(l, self.queryList(0))
  173.  
  174.     
  175.     def child(self, path):
  176.         '''Construct a url where the given path segment is a child of this url
  177.         '''
  178.         l = self.pathList()
  179.         if l[-1] == '':
  180.             l[-1] = path
  181.         else:
  182.             l.append(path)
  183.         return self._pathMod(l, self.queryList(0))
  184.  
  185.     
  186.     def isRoot(self, pathlist):
  187.         if not pathlist == [
  188.             '']:
  189.             pass
  190.         return not pathlist
  191.  
  192.     
  193.     def parent(self):
  194.         import warnings as warnings
  195.         warnings.warn('[v0.4] URL.parent has been deprecated and replaced with parentdir (which does what parent used to do) and up (which does what you probably thought parent would do ;-))', DeprecationWarning, stacklevel = 2)
  196.         return self.parentdir()
  197.  
  198.     
  199.     def curdir(self):
  200.         """Construct a url which is a logical equivalent to '.'
  201.         of the current url. For example:
  202.  
  203.         >>> print URL.fromString('http://foo.com/bar').curdir()
  204.         http://foo.com/
  205.         >>> print URL.fromString('http://foo.com/bar/').curdir()
  206.         http://foo.com/bar/
  207.         """
  208.         l = self.pathList()
  209.         if l[-1] != '':
  210.             l[-1] = ''
  211.         
  212.         return self._pathMod(l, self.queryList(0))
  213.  
  214.     
  215.     def up(self):
  216.         '''Pop a URL segment from this url.
  217.         '''
  218.         l = self.pathList()
  219.         if len(l):
  220.             l.pop()
  221.         
  222.         return self._pathMod(l, self.queryList(0))
  223.  
  224.     
  225.     def parentdir(self):
  226.         """Construct a url which is the parent of this url's directory;
  227.         This is logically equivalent to '..' of the current url.
  228.         For example:
  229.  
  230.         >>> print URL.fromString('http://foo.com/bar/file').parentdir()
  231.         http://foo.com/
  232.         >>> print URL.fromString('http://foo.com/bar/dir/').parentdir()
  233.         http://foo.com/bar/
  234.         """
  235.         l = self.pathList()
  236.         if not self.isRoot(l) and l[-1] == '':
  237.             del l[-2]
  238.         else:
  239.             l.pop()
  240.             if self.isRoot(l):
  241.                 l.append('')
  242.             else:
  243.                 l[-1] = ''
  244.         return self._pathMod(l, self.queryList(0))
  245.  
  246.     
  247.     def click(self, href):
  248.         """Build a path by merging 'href' and this path.
  249.  
  250.         Return a path which is the URL where a browser would presumably
  251.         take you if you clicked on a link with an 'href' as given.
  252.         """
  253.         (scheme, netloc, path, query, fragment) = urlparse.urlsplit(href)
  254.         if (scheme, netloc, path, query, fragment) == ('', '', '', '', ''):
  255.             return self
  256.         query = unquerify(query)
  257.         if scheme:
  258.             if path and path[0] == '/':
  259.                 path = path[1:]
  260.             
  261.             return self.cloneURL(scheme, netloc, map(raw, path.split('/')), query, fragment)
  262.         scheme = self.scheme
  263.         path = normURLPath(path)
  264.         return self.cloneURL(scheme, netloc, map(raw, path.split('/')), query, fragment)
  265.  
  266.     
  267.     def queryList(self, copy = True):
  268.         '''Return current query as a list of tuples.'''
  269.         if copy:
  270.             return self._querylist[:]
  271.         return self._querylist
  272.  
  273.     
  274.     def add(self, name, value = None):
  275.         '''Add a query argument with the given value
  276.         None indicates that the argument has no value
  277.         '''
  278.         q = self.queryList()
  279.         q.append((name, value))
  280.         return self._pathMod(self.pathList(copy = False), q)
  281.  
  282.     
  283.     def replace(self, name, value = None):
  284.         """
  285.         Remove all existing occurrences of the query argument 'name', *if it
  286.         exists*, then add the argument with the given value.
  287.  
  288.         C{None} indicates that the argument has no value.
  289.         """
  290.         ql = self.queryList(False)
  291.         i = 0
  292.         for k, v in ql:
  293.             if k == name:
  294.                 break
  295.             
  296.             i += 1
  297.         
  298.         q = (filter,)((lambda x: x[0] != name), ql)
  299.         q.insert(i, (name, value))
  300.         return self._pathMod(self.pathList(copy = False), q)
  301.  
  302.     
  303.     def remove(self, name):
  304.         '''Remove all query arguments with the given name
  305.         '''
  306.         return self._pathMod(self.pathList(copy = False), (filter,)((lambda x: x[0] != name), self.queryList(False)))
  307.  
  308.     
  309.     def clear(self, name = None):
  310.         '''Remove all existing query arguments
  311.         '''
  312.         if name is None:
  313.             q = []
  314.         else:
  315.             q = (filter,)((lambda x: x[0] != name), self.queryList(False))
  316.         return self._pathMod(self.pathList(copy = False), q)
  317.  
  318.     
  319.     def secure(self, secure = True, port = None):
  320.         """Modify the scheme to https/http and return the new URL.
  321.  
  322.         @param secure: choose between https and http, default to True (https)
  323.         @param port: port, override the scheme's normal port
  324.         """
  325.         if secure:
  326.             (scheme, defaultPort) = ('https', 443)
  327.         else:
  328.             (scheme, defaultPort) = ('http', 80)
  329.         netloc = self.netloc.split(':', 1)[0]
  330.         if port is not None and port != defaultPort:
  331.             netloc = '%s:%d' % (netloc, port)
  332.         
  333.         return self.cloneURL(scheme, netloc, self._qpathlist, self._querylist, self.fragment)
  334.  
  335.     
  336.     def anchor(self, anchor = None):
  337.         """
  338.         Modify the fragment/anchor and return a new URL. An anchor of
  339.         C{None} (the default) or C{''} (the empty string) will remove the
  340.         current anchor.
  341.         """
  342.         return self.cloneURL(self.scheme, self.netloc, self._qpathlist, self._querylist, anchor)
  343.  
  344.     
  345.     def __str__(self):
  346.         return str(flat.flatten(self))
  347.  
  348.     
  349.     def __repr__(self):
  350.         return '%s(scheme=%r, netloc=%r, pathsegs=%r, querysegs=%r, fragment=%r)' % (self.__class__, self.scheme, self.netloc, self._qpathlist, self._querylist, self.fragment)
  351.  
  352.  
  353.  
  354. def normURLPath(path):
  355.     """
  356.     Normalise the URL path by resolving segments of '.' and '..'.
  357.     """
  358.     segs = []
  359.     pathSegs = path.split('/')
  360.     for seg in pathSegs:
  361.         None if seg == '.' else segs
  362.         segs.append(seg)
  363.     
  364.     if pathSegs[-1:] in ([
  365.         '.'], [
  366.         '..']):
  367.         segs.append('')
  368.     
  369.     return '/'.join(segs)
  370.  
  371.  
  372. class URLOverlay(object):
  373.     
  374.     def __init__(self, urlaccessor, doc = None, dolater = None, keep = None):
  375.         """A Proto like object for abstractly specifying urls in stan trees.
  376.  
  377.         @param urlaccessor: a function which takes context and returns a URL
  378.  
  379.         @param doc: a a string documenting this URLOverlay instance's usage
  380.  
  381.         @param dolater: a list of tuples of (command, args, kw) where
  382.         command is a string, args is a tuple and kw is a dict; when the
  383.         URL is returned from urlaccessor during rendering, these
  384.         methods will be applied to the URL in order
  385.         """
  386.         if doc is not None:
  387.             self.__doc__ = doc
  388.         
  389.         self.urlaccessor = urlaccessor
  390.         if dolater is None:
  391.             dolater = []
  392.         
  393.         self.dolater = dolater
  394.         if keep is None:
  395.             keep = []
  396.         
  397.         self._keep = keep
  398.  
  399.     
  400.     def addCommand(self, cmd, args, kw):
  401.         dl = self.dolater[:]
  402.         dl.append((cmd, args, kw))
  403.         return self.__class__(self.urlaccessor, dolater = dl, keep = self._keep[:])
  404.  
  405.     
  406.     def keep(self, *args):
  407.         '''A list of arguments to carry over from the previous url.
  408.         '''
  409.         K = self._keep[:]
  410.         K.extend(args)
  411.         return self.__class__(self.urlaccessor, dolater = self.dolater[:], keep = K)
  412.  
  413.  
  414.  
  415. def createForwarder(cmd):
  416.     return (lambda self: self.addCommand(cmd, args, kw))
  417.  
  418. for cmd in [
  419.     'sibling',
  420.     'child',
  421.     'parent',
  422.     'here',
  423.     'curdir',
  424.     'click',
  425.     'add',
  426.     'replace',
  427.     'clear',
  428.     'remove',
  429.     'secure',
  430.     'anchor',
  431.     'up',
  432.     'parentdir']:
  433.     setattr(URLOverlay, cmd, createForwarder(cmd))
  434.  
  435.  
  436. def hereaccessor(context):
  437.     return URL.fromContext(context).clear()
  438.  
  439. here = URLOverlay(hereaccessor, "A lazy url construction object representing the current page's URL. The URL which will be used will be determined at render time by looking at the request. Any query parameters will be cleared automatically.")
  440.  
  441. def gethereaccessor(context):
  442.     return URL.fromContext(context)
  443.  
  444. gethere = URLOverlay(gethereaccessor, "A lazy url construction object like 'here' except query parameters are preserved. Useful for constructing a URL to this same object when query parameters need to be preserved but modified slightly.")
  445.  
  446. def viewhereaccessor(context):
  447.     U = hereaccessor(context)
  448.     i = 1
  449.     while True:
  450.         
  451.         try:
  452.             params = context.locate(inevow.IViewParameters, depth = i)
  453.         except KeyError:
  454.             break
  455.  
  456.         for cmd, args, kw in iter(params):
  457.             U = getattr(U, cmd)(*args, **kw)
  458.         
  459.         i += 1
  460.     return U
  461.  
  462. viewhere = URLOverlay(viewhereaccessor, "A lazy url construction object like 'here' IViewParameters objects are looked up in the context during rendering. Commands provided by any found IViewParameters objects are applied to the URL object before rendering it.")
  463.  
  464. def rootaccessor(context):
  465.     req = context.locate(inevow.IRequest)
  466.     root = req.getRootURL()
  467.     if root is None:
  468.         return URL.fromContext(context).click('/')
  469.     return URL.fromString(root)
  470.  
  471. root = URLOverlay(rootaccessor, "A lazy URL construction object representing the root of the application. Normally, this will just be the logical '/', but if request.rememberRootURL() has previously been used in the request traversal process, the url of the resource where rememberRootURL was called will be used instead.")
  472.  
  473. def URLSerializer(original, context):
  474.     '''
  475.     Serialize the given L{URL}.
  476.  
  477.     Unicode path, query and fragment components are handled according to the
  478.     IRI standard (RFC 3987).
  479.     '''
  480.     
  481.     def _maybeEncode(s):
  482.         if isinstance(s, unicode):
  483.             s = s.encode('utf-8')
  484.         
  485.         return s
  486.  
  487.     urlContext = WovenContext(parent = context, precompile = context.precompile, inURL = True)
  488.     if original.scheme:
  489.         yield '%s://%s' % (original.scheme, original.netloc)
  490.     
  491.     for pathsegment in original._qpathlist:
  492.         yield '/'
  493.         yield serialize(_maybeEncode(pathsegment), urlContext)
  494.     
  495.     query = original._querylist
  496.     if query:
  497.         yield '?'
  498.         first = True
  499.         for key, value in query:
  500.             if not first:
  501.                 if context.isAttrib is True:
  502.                     yield '&'
  503.                 else:
  504.                     yield '&'
  505.             else:
  506.                 first = False
  507.             yield serialize(_maybeEncode(key), urlContext)
  508.             if value is not None:
  509.                 yield '='
  510.                 yield serialize(_maybeEncode(value), urlContext)
  511.                 continue
  512.         
  513.     
  514.     if original.fragment:
  515.         yield '#'
  516.         yield serialize(_maybeEncode(original.fragment), urlContext)
  517.     
  518.  
  519.  
  520. def URLOverlaySerializer(original, context):
  521.     if context.precompile:
  522.         yield original
  523.     else:
  524.         url = original.urlaccessor(context)
  525.         for cmd, args, kw in original.dolater:
  526.             url = getattr(url, cmd)(*args, **kw)
  527.         
  528.         req = context.locate(inevow.IRequest)
  529.         for key in original._keep:
  530.             for value in req.args.get(key, []):
  531.                 url = url.add(key, value)
  532.             
  533.         
  534.         yield serialize(url, context)
  535.  
  536.  
  537. class URLGenerator:
  538.     
  539.     def __init__(self):
  540.         self._objmap = weakref.WeakKeyDictionary()
  541.  
  542.     
  543.     def objectMountedAt(self, obj, at):
  544.         self._objmap[obj] = at
  545.  
  546.     
  547.     def url(self, obj):
  548.         
  549.         try:
  550.             return self._objmap.get(obj, None)
  551.         except TypeError:
  552.             return None
  553.  
  554.  
  555.     __call__ = url
  556.     
  557.     def __getstate__(self):
  558.         d = self.__dict__.copy()
  559.         del d['_objmap']
  560.         return d
  561.  
  562.     
  563.     def __setstate__(self, state):
  564.         self.__dict__ = state
  565.         self._objmap = weakref.WeakKeyDictionary()
  566.  
  567.  
  568.  
  569. class URLRedirectAdapter:
  570.     """Adapter for URL and URLOverlay instances that results in an HTTP
  571.     redirect.
  572.  
  573.     Whenever a URL or URLOverlay instance is returned from locateChild or
  574.     renderHTTP an HTTP response is generated that causes a redirect to
  575.     the adapted URL. Any remaining segments of the current request are
  576.     consumed.
  577.  
  578.     Note that URLOverlay instances are lazy so their use might not be entirely
  579.     obvious when returned from locateChild, i.e. url.here means the request's
  580.     URL and not the URL of the resource that is self.
  581.  
  582.         def renderHTTP(self, ctx):
  583.             # Redirect to my immediate parent
  584.             return url.here.up()
  585.  
  586.         def locateChild(self, ctx, segments):
  587.             # Redirect to the URL of this resource
  588.             return url.URL.fromContext(ctx)
  589.     """
  590.     implements(inevow.IResource)
  591.     
  592.     def __init__(self, original):
  593.         self.original = original
  594.  
  595.     
  596.     def locateChild(self, ctx, segments):
  597.         return (self, ())
  598.  
  599.     
  600.     def renderHTTP(self, ctx):
  601.         bits = []
  602.         
  603.         def flattened(spam):
  604.             u = ''.join(bits)
  605.             u = flat.flatten(URL.fromContext(ctx).click(u), ctx)
  606.             return redirectTo(u, inevow.IRequest(ctx))
  607.  
  608.         return flat.flattenFactory(self.original, ctx, bits.append, flattened)
  609.  
  610.  
  611.